<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <CommonQueryFormBar v-model="queryParams" @query="handleQuery" @reset="resetQuery">
      <template #default>
        <el-form-item label="昵称" prop="nickname">
          <el-input
            v-model="queryParams.nickname"
            class="!w-240px"
            clearable
            placeholder="请输入用户昵称"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input
            v-model="queryParams.mobile"
            class="!w-240px"
            clearable
            placeholder="请输入手机号"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="会员等级" prop="userLevel" v-if="routerTitle === '会员管理'">
          <el-select
            v-model="queryParams.userLevel"
            placeholder="请选择会员等级"
            clearable
            class="!w-240px"
          >
            <el-option
              v-for="dict in getIntDictOptions(DICT_TYPE.MEMBER_LEVEL)"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
      </template>

      <template #more>
        <el-form-item label="性别" prop="sex">
          <el-select v-model="queryParams.sex" placeholder="请选择性别" clearable class="!w-240px">
            <el-option
              v-for="dict in getIntDictOptions(DICT_TYPE.SYSTEM_USER_SEX)"
              :key="dict.value"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input
            v-model="queryParams.age"
            clearable
            placeholder="请输入年龄"
            @keyup.enter="handleQuery"
          />
        </el-form-item>

        <el-form-item label="婚况" prop="marriage">
          <CommonSelect
            v-model="queryParams.marriage"
            :options="hkOptions"
            placeholder="请选择婚况"
          />
        </el-form-item>
        <el-form-item label="有孩子" prop="withChild">
          <CommonSelect
            v-model="queryParams.withChild"
            :options="chooseTwoOptions"
            placeholder="请选择"
          />
        </el-form-item>
        <el-form-item label="想要孩子" prop="wantChild">
          <CommonSelect
            v-model="queryParams.wantChild"
            :options="chooseTwoOptions"
            placeholder="请选择"
          />
        </el-form-item>
        <el-form-item label="是否购车" prop="car">
          <CommonSelect
            v-model="queryParams.car"
            :options="chooseTwoOptions"
            placeholder="请选择"
          />
        </el-form-item>
        <el-form-item label="是否购房" prop="house">
          <CommonSelect
            v-model="queryParams.house"
            :options="chooseTwoOptions"
            placeholder="请选择"
          />
        </el-form-item>
        <el-form-item label="学历" prop="educationAttainment">
          <CommonSelect
            v-model="queryParams.educationAttainment"
            :options="educationOptions"
            placeholder="请选择学历"
          />
        </el-form-item>
        <el-form-item label="是否吸烟" prop="smoking">
          <CommonSelect
            v-model="queryParams.smoking"
            :options="chooseTwoOptions"
            placeholder="请选择"
          />
        </el-form-item>
        <el-form-item label="是否喝酒" prop="drink">
          <CommonSelect
            v-model="queryParams.drink"
            :options="chooseTwoOptions"
            placeholder="请选择"
          />
        </el-form-item>
        <el-form-item label="结婚时间" prop="timeOfMarriage">
          <el-date-picker
            v-model="queryParams.timeOfMarriage"
            class="!w-240px"
            type="date"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
      </template>
    </CommonQueryFormBar>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
      v-loading="loading"
      :data="list"
      :show-overflow-tooltip="true"
      :stripe="true"
      @selection-change="handleSelectionChange"
    >
      <el-table-column align="center" label="会员编号" prop="userNo" />
      <el-table-column align="center" label="会员ID" prop="id" />
      <el-table-column align="center" label="昵称" prop="nickname" />
      <el-table-column align="center" label="姓名" prop="name" />
      <el-table-column
        align="center"
        label="性别"
        prop="sex"
        :formatter="sexFormatter"
        width="80px"
      >
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.SYSTEM_USER_SEX" :value="scope.row.sex" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="年龄" prop="age" width="80px" />
      <el-table-column align="center" label="婚况" prop="marriage" width="100px">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.MARITAL_STATUS" :value="scope.row.sex" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="手机号" prop="mobile" width="120px" />
      <el-table-column
        align="center"
        label="会员等级"
        prop="userLevel"
        width="100px"
        v-if="routerTitle === '会员管理'"
      >
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.MEMBER_LEVEL" :value="scope.row.userLevel" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="手机号" prop="mobile" width="120px" />
      <el-table-column align="center" label="会员等级" prop="userLevel" width="100px" />
      <el-table-column
        :formatter="dateFormatter"
        align="center"
        label="到期时间"
        prop="memberEndTime"
        width="180px"
        v-if="routerTitle === '会员管理'"
      />
      <el-table-column
        :show-overflow-tooltip="false"
        align="center"
        fixed="right"
        label="操作"
        width="200px"
      >
        <template #default="scope">
          <div class="flex items-center justify-center">
            <el-button link type="primary" @click="openDetail(scope.row.id)">详情</el-button>
            <el-button
              link
              type="primary"
              @click="openForm('update', scope.row.id)"
              v-hasPermi="['member:user:update']"
            >
              编辑
            </el-button>
            <el-button
              link
              type="danger"
              @click="handleDelete(scope.row.id)"
              v-hasPermi="['system:user:delete']"
            >
              删除
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      v-model:limit="queryParams.pageSize"
      v-model:page="queryParams.pageNo"
      :total="total"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <UserForm ref="formRef" @success="getList" />
  <!-- 修改用户等级弹窗 -->
  <UserLevelUpdateForm ref="updateLevelFormRef" @success="getList" />
  <!-- 修改用户积分弹窗 -->
  <UserPointUpdateForm ref="updatePointFormRef" @success="getList" />
</template>

<script lang="ts" setup>
import { sexFormatter } from '@/utils/formatter'
import { dateFormatter } from '@/utils/formatTime'
import * as UserApi from '@/api/member/user'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import UserForm from './UserForm.vue'
import UserLevelUpdateForm from './UserLevelUpdateForm.vue'
import UserPointUpdateForm from './UserPointUpdateForm.vue'

defineOptions({ name: 'MemberUser' })
const router = useRouter()
const routerTitle = router.currentRoute.value.meta.title

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref([]) // 列表的数据
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  nickname: null,
  mobile: null,
  loginDate: [],
  createTime: [],
  tagIds: [],
  levelId: null,
  userLevel: null,
  groupId: null,
  sex: null,
  age: null,
  hunKuang: null,
  chindren: null,
  car: null,
  house: null,
  educationAttainment: null,
  smoking: null,
  drink: null,
  timeOfMarriage: null,
  marriage: null,
  withChild: null,
  wantChild: null,
  haveMember: routerTitle === '会员管理' ? 1 : 0
})
const sexOptions = [
  {
    value: '1',
    label: '男'
  },
  {
    value: '2',
    label: '女'
  }
]
const hkOptions = [
  {
    value: '1',
    label: '已婚'
  },
  {
    value: '0',
    label: '未婚'
  }
]
const chooseTwoOptions = [
  {
    value: '1',
    label: '是'
  },
  {
    value: '0',
    label: '否'
  }
]
const educationOptions = [
  {
    value: '0',
    label: '无'
  },
  {
    value: '1',
    label: '小学'
  },
  {
    value: '2',
    label: '初中'
  },
  {
    value: '3',
    label: '高中'
  },
  {
    value: '4',
    label: '专科'
  },
  {
    value: '5',
    label: '本科'
  },
  {
    value: '6',
    label: '研究生'
  },
  {
    value: '7',
    label: '博士'
  }
]
const updateLevelFormRef = ref() // 修改会员等级表单
const updatePointFormRef = ref() // 修改会员积分表单
const selectedIds = ref<number[]>([]) // 表格的选中 ID 数组

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await UserApi.getUserPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  handleQuery()
}

/** 打开会员详情 */
const { push } = useRouter()
const openDetail = (id: number) => {
  push({ name: 'MemberUserDetail', params: { id } })
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 表格选中事件 */
const handleSelectionChange = (rows: UserApi.UserVO[]) => {
  selectedIds.value = rows.map((row) => row.id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await UserApi.deleteUser(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 操作分发 */
const handleCommand = (command: string, row: UserApi.UserVO) => {
  switch (command) {
    case 'handleUpdate':
      openForm('update', row.id)
      break
    case 'handleUpdateLevel':
      updateLevelFormRef.value.open(row.id)
      break
    case 'handleUpdatePoint':
      updatePointFormRef.value.open(row.id)
      break
    case 'handleUpdateBlance':
      // todo @jason：增加一个【修改余额】
      break
    case 'handleDelete':
      handleDelete(row.id)
      break
    default:
      break
  }
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>
